package com.example.webdemo.service;

import com.example.webdemo.bean.product;
import com.example.webdemo.exception.InsufficientStockException;
import com.example.webdemo.exception.ResourceNotFoundException;
import com.example.webdemo.dao.ProductDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductService {

    private final ProductDao productDao;
    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public ProductService(ProductDao productDao, JdbcTemplate jdbcTemplate) {
        this.productDao = productDao;
        this.jdbcTemplate = jdbcTemplate;
    }

    public product createProduct(product product) {
        int id = productDao.save(product);
        product.setProd_id(id);
        return product;
    }

    public product updateProduct(int id, product product) {
        product.setProd_id(id);
        int updated = productDao.update(product);
        if (updated == 0) {
            throw new ResourceNotFoundException("Product not found with id: " + id);
        }
        return product;
    }

    public void deleteProduct(int id) {
        int deleted = productDao.delete(id);
        if (deleted == 0) {
            throw new ResourceNotFoundException("Product not found with id: " + id);
        }
    }

    public product getProductById(int id) {
        return productDao.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Product not found with id: " + id));
    }

    public List<product> getAllProducts() {
        return productDao.findAll();
    }

    public List<product> searchProducts(String name, String category, Integer status) {
        return productDao.searchProducts(name, category, status);
    }

    // 商品库存操作
    public void increaseStock(int productId, int quantity) {
        String sql = "UPDATE product SET stock = stock + ? WHERE id = ?";
        int updated = jdbcTemplate.update(sql, quantity, productId);
        if (updated == 0) {
            throw new ResourceNotFoundException("Product not found with id: " + productId);
        }
    }

    public void decreaseStock(int productId, int quantity) {
        String sql = "UPDATE product SET stock = stock - ? WHERE id = ? AND stock >= ?";
        int updated = jdbcTemplate.update(sql, quantity, productId, quantity);
        if (updated == 0) {
            // 可能是库存不足或商品不存在
            product product = getProductById(productId);
            if (product.getProd_status() < quantity) {
                throw new InsufficientStockException("Insufficient stock for product: " + product.getProd_name());
            }
        }
    }
}

